#pragma once
#include <vector>
#include <queue>
#include <pthread.h>
#include <string>
#include <unistd.h>

//换为封装的线程
struct ThreadInfo
{
    pthread_t _tid;
    std::string _name;
};
template <class T>
class pool
{
    static const int defaultnum = 5;

public:
   

    std::string getname(pthread_t tid)
    {
        for (auto ch : _thread)
        {
            if (ch._tid == tid)
            {
                return ch._name;
            }
        }
        return "None";
    }
    static void* HandlerTask(void* args)
    {
        pool<T> *tp = static_cast<pool<T> *>(args);
        std::string name = tp->getname(pthread_self());
        while (true)
        {
            pthread_mutex_lock(&(tp->_mutex));
            while (tp->_que.empty())
            {
                pthread_cond_wait(&(tp->_cond), &(tp->_mutex));
            }
            T t = tp->_que.front();
            tp->_que.pop();
            pthread_mutex_unlock(&tp->_mutex);
            t.run();
            printf("%s finsih task:%s\n", name.c_str(), t.getresult().c_str());
            sleep(1);
        }
        }
    void start()
    {
        for (int i = 0; i < _thread.size(); i++)
        {
            _thread[i]._name = "thread" + std::to_string(i);
            pthread_create(&_thread[i]._tid, nullptr, HandlerTask, this);
        }
    }

    void push(const T& x)
    {
        pthread_mutex_lock(&_mutex);
        _que.push(x);
        pthread_cond_signal(&_cond);
        pthread_mutex_unlock(&_mutex);
    }
    
    static pool<T>* GetInstance()
    {
        //套一层判断,只有第一次需要上锁
        if (_pl == nullptr)
        {
            pthread_mutex_lock(&_lock);
            if (_pl == nullptr)
            {
                printf("first create\n");
                _pl = new pool<T>;
            }
            pthread_mutex_unlock(&_lock);
        }

        return _pl;
    }

private:
//构造私有化
    pool(int num = defaultnum)
        : _thread(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    pool(const pool<T> &) = delete;
    const pool<T> &operator=(const pool<T>&) = delete;
    ~pool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }
    std::vector<ThreadInfo> _thread;
    std::queue<T> _que;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static pthread_mutex_t _lock;
    static pool<T> *_pl;
};

//类外初始化
template <class T>
pool<T>* pool<T>::_pl = nullptr;
template <class T>
pthread_mutex_t pool<T>::_lock = PTHREAD_MUTEX_INITIALIZER;